package ssm.service;

import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ssm.dao.MyResult;
import ssm.dao.User;
import ssm.model.UserMapper;
import ssm.utils.Const;
import ssm.utils.MD5Util;
import ssm.utils.TokenCache;

import javax.servlet.http.HttpSession;
import java.util.UUID;

@Service
public class UserServiceImpl implements  UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public MyResult login(String username, String password,HttpSession session) {
        int resultCount=userMapper.checkUsername(username);
        if(resultCount==0){
            return MyResult.except("数据库中查找不到对应用户数据","用户名不存在");
        }
        //ok 密码登录MD5
        String md5Password= MD5Util.MD5EncodeUtf8(password);
        System.out.println("md5Password:"+md5Password);
        User user=userMapper.selectLogin(username,md5Password);
        if(user==null){
            return MyResult.except("用户存在,但密码匹配不上","密码错误");
        }
        user.setPassword(null);
        session.setAttribute(Const.CURRENT_USER,user);
        return MyResult.ok(user);
    }

    @Override
    public MyResult register(User user) {
        MyResult myResult = checkValid(user.getUsername(), Const.USERNAME);
        if(myResult.getStatus()==202){
            return myResult;
        }
        myResult=checkValid(user.getEmail(),Const.EMAIL);
        if(myResult.getStatus()==202){
            return myResult;
        }
        user.setRole(Const.Role.TEACHER.getStatus());
        //MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int resultCount = userMapper.insert(user);
        if(resultCount==0){
            return MyResult.except("未知原因导致的数据插入失败,提醒用户稍后重试","注册失败,请稍后再试");
        }
        return  MyResult.ok("注册成功");
    }

    @Override
    public MyResult checkValid(String str, String type) {
        if(StringUtils.isNotBlank(str)){
            if(Const.USERNAME.equals(type)){
                int resultUsernameCount=userMapper.checkUsername(str);
                if(resultUsernameCount>0){
                    return MyResult.except("提醒注册人,该用户名已被注册","用户名已存在");
                }
            }
            if(Const.EMAIL.equals(type)){
                int resultEmailCount=userMapper.checkEmail(str);
                if(resultEmailCount>0){
                    return MyResult.except("提醒注册人,该邮箱已被注册","邮箱已存在");
                }
            }
        }else{
            return MyResult.except("传入参数异常","参数错误");
        }
        return MyResult.ok("校验成功");
    }


    @Override
    public MyResult selectGetQuest(String username) {
        MyResult response=checkValid(username,Const.USERNAME);
        if(response.getStatus()==202){
            return MyResult.except("数据库中查找不到对应用户","该用户不存在");
        }
        String question=userMapper.selectGetQuestByUsername(username);
        if(StringUtils.isNotBlank(question)){
            return MyResult.ok(question);
        }
        return MyResult.except("提醒用户设置问题","用户问题尚未设置");
    }

    @Override
    public MyResult forgetAnswer(String username, String question, String answer) {
        int resultCount = userMapper.forgetAnswer(username, question, answer);
        if (resultCount > 0) {
            //说明问题以及问题答案是这个用户的,并且是正确的答案
            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX + username, forgetToken);
            return MyResult.ok(forgetToken);
        }
        return MyResult.except("答案匹配不上","问题的答案错误");
    }

    @Override
    public MyResult forgetRestPassword(String username, String newPassword, String token) {
        String checkToken=TokenCache.getKey(username);
        int resultCount=0;
        newPassword=MD5Util.MD5EncodeUtf8(newPassword);
        if(StringUtils.isNotBlank(token)){
            return MyResult.except("遗忘密码-修改密码时,传入token为空","参数错误,需要上传token值");
        }

        MyResult validUser=checkValid(username,Const.USERNAME);

        if(validUser.getStatus()==202){
            return MyResult.except("用户不存在","用户不存在");
        }


        if((TokenCache.TOKEN_PREFIX+username).equals(token)){
            resultCount=userMapper.forgetRestPassword(username,newPassword);
        }else{
            return MyResult.except("用户停留在修改页面过久,导致超时,提醒用户重来","修改密码超时,请重新尝试");
        }
        if(resultCount>0){
            return  MyResult.ok("密码修改成功");
        }
        return MyResult.except("未知原因发生异常,数据未更新成功","密码修改失败");
    }

    @Override
    public MyResult checkPasswordRepeat(String username, String newPassword) {
        MyResult validUser=checkValid(username,"username");
        if(validUser.getStatus()==202){
            return  MyResult.except("用户不存在");
        }
        if(!StringUtils.isNotBlank(newPassword)){
            return MyResult.except("密码不能为空");
        }
        newPassword=MD5Util.MD5EncodeUtf8(newPassword);
        int resultCount=userMapper.findReapetByPassword(username,newPassword);
        if(resultCount>1){
            return MyResult.except("新密码不能与旧密码相同");
        }

        return MyResult.ok();
    }

    @Override
    public MyResult resetPassword(User user, String oldPassword, String newPassword) {
        MyResult validUser=checkValid(user.getUsername(),"username");
        if(validUser.getStatus()==202){
            return  MyResult.except("用户不存在");
        }
        if(!StringUtils.isNotBlank(oldPassword)){
            return MyResult.except("旧密码不能为空");
        }
        if(!StringUtils.isNotBlank(newPassword)){
            return  MyResult.except("新密码不能为空");
        }
        if(newPassword.equals(oldPassword)){
            return MyResult.except("新密码不能与旧密码相同");
        }
        oldPassword= MD5Util.MD5EncodeUtf8(oldPassword);
        newPassword= MD5Util.MD5EncodeUtf8(newPassword);
        int resultCount=userMapper.checkPassword(user.getId(),oldPassword);
        if(resultCount==0){
            return MyResult.except("密码错误");
        }
        user.setPassword(newPassword);
        resultCount=userMapper.updateByPrimaryKeySelective(user);
        if(resultCount>0){
            return  MyResult.ok("密码修改成功");
        }
        return MyResult.except("修改出错,请重新尝试");
    }

    @Override
    public MyResult update_information(User user) {
        //判断修改邮箱是否被占用
        int resultCount=userMapper.checkEmailByUserId(user.getId(),user.getEmail());
        if(resultCount>0){
            return MyResult.except("Email已存在,请更换邮箱后再尝试");
        }
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());
        resultCount = userMapper.updateByPrimaryKeySelective(user);
        if(resultCount>0){
            return MyResult.ok(updateUser);
        }
        return MyResult.except("更新个人信息失败");

    }

    @Override
    public MyResult getInformation(int userid) {
        User user=userMapper.getInformation(userid);
        if(user==null){
            return MyResult.except("用户不存在");
        }
        user.setPassword("");
        return MyResult.ok(user);

    }

    @Override
    public MyResult checkAdmin(User user) {
        if(user!=null && user.getRole().intValue()==Const.Role.LEAP.getStatus()){
            return MyResult.ok();
        }
        return MyResult.except("无权限操作,需要管理员权限");
    }
}
